<?php

namespace app\service;
use app\tool\Curl;
use think\facade\Db;

class UniIdService
{

    private $requestAuthSecret;
    public function __construct ($requestAuthSecret) {
        $this->requestAuthSecret = $requestAuthSecret;
    }

    public function getSignature ($params, $nonce, $timestamp) {
        $paramsStr = $this->getParamsString($params);
        $signature = hash_hmac('sha256', ((string)$timestamp . $paramsStr), ($this->requestAuthSecret . $nonce));
        return strtoupper($signature);
    }

    private function getParamsString ($params) {
        ksort($params);
        $paramsStr = [];
        foreach($params as $key=>$value){
            if (gettype($value) == "array" || gettype($value) == "object") {
                continue;
            }
            array_push($paramsStr, $key . '=' . $value);
        }
        return join('&', $paramsStr);
    }

    public static function curlUniId($params,$path)
    {
        $config=config('UniIm');
        $requestAuthSecret = $config['requestAuthSecret'];
        $nonce = sprintf("%d", rand());
        $timestamp = time() * 1000;
        $sign = new UniIdService($requestAuthSecret);
        $signature = $sign->getSignature($params, $nonce, $timestamp);
        $host=$config['baseURL'].$path;
        return Curl::curl($host,[
                "clientInfo"=> [
                    'uniPlatform'=>$config['appPlatform'],
                    'appId'=>$config['appId'],
                ],'params'=>$params],
                [
                    'uni-id-nonce'=>$nonce,
                    'uni-id-timestamp'=>$timestamp,
                    'uni-id-signature'=>$signature,
                    'Content-Type' =>'application/json',
                    'Cache-Control'=> 'no-cache'
                ]
        );
    }

}
